<template>
  <div class="w-100% h-100% flex">
    <div
      class="w-300 h-100% box-border pr-8 b-r-1 b-r-solid b-r-#f0f2f5 m-r-12"
    >
      <!-- header -->
      <div class="flex w-100% items-center h-40">
        <el-input
          size="mini"
          prefix-icon="el-icon-search"
          class="mr-8"
          v-model="search"
        ></el-input>
        <el-button
          size="mini"
          icon="el-icon-plus"
          type="primary"
          @click="handleOpenAdd"
        ></el-button>
      </div>
      <!-- list -->
      <div class="w-100% overflow-auto" style="height: calc(100% - 40px)">
        <p
          v-for="item in filterList"
          :key="item.name"
          @click="() => handleSelectItem(item)"
          class="w-100% mb-8 cursor-pointer"
        >
          <el-tag
            :type="currentPage.name == item.name ? 'primary' : 'info'"
            class="w-100%"
            >{{ item.name }}</el-tag
          >
        </p>
      </div>
    </div>
    <!-- content -->
    <div class="flex-1 h-100% bg-#f0f2f5">
      <div
        class="h-40 p-x-16 box-border w-100% flex items-center justify-between"
      >
        <div class="fw-600 text-18">表单配置</div>
        <div>
          <el-button
            :disabled="!currentPage.name"
            size="mini"
            icon="el-icon-view"
            @click="handlePreview"
            >预览</el-button
          >
          <el-button size="mini" icon="el-icon-check" @click="handleSave" :disabled="!currentPage.name"
            >保存</el-button
          >
          <el-button size="mini" icon="el-icon-delete" @click="handleDelete" :disabled="!currentPage.name"
            >删除</el-button
          >
          <el-button size="mini" icon="el-icon-download" @click="handleDown" :disabled="!currentPage.name"
            >下载</el-button
          >
          <el-button size="mini" icon="el-icon-upload" @click="loadvisible = true"
            >载入页面数据</el-button
          >
        </div>
      </div>
      <!-- 表单层 -->
      <div
        class="w-100% overflow-auto box-border p-16"
        style="height: calc(100% - 40px)"
      >
        <el-form
          v-if="currentPage.name"
          :model="currentPage"
          size="mini"
          label-position="left"
          label-width="200"
        >
          <el-form-item label="名称" prop="name">
            <el-input disabled v-model="currentPage.name"></el-input>
          </el-form-item>
          <el-form-item label="样式" prop="class">
            <el-input type="textarea" v-model="currentPage.class"></el-input>
          </el-form-item>
          <form-items
            label="边框"
            v-model="currentPage.border"
            :column="borderColumn"
          ></form-items>
          <form-items
            label="分栏"
            v-model="currentPage.layout"
            :column="layoutColumn"
          ></form-items>
          <form-set
            v-model="currentPage.content"
            label="页面内容"
            :column="contentColumn"
            @change-type="handleTypeSelect"
          ></form-set>
        </el-form>
      </div>
    </div>

    <!-- dialog -->
    <el-dialog class="" title="新增页面" :visible.sync="addvisible">
      <el-form>
        <el-form-item label="名称" prop="name">
          <el-input v-model="formPage.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="addvisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="handleAdd">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      class=""
      :visible.sync="viewvisible"
      width="80%"
      top="6vh"
      destroy-on-close
      title="预览页面"
    >
      <div
        class="h-80vh w-100% relative overflow-auto"
        :style="`background:${viewBg}`"
      >
        <box-page v-bind="viewData"></box-page>
      </div>
    </el-dialog>

    <el-dialog title="载入页面数据" :visible.sync="loadvisible" width="400px">
      <el-upload
        class="upload-demo"
        action=""
        :auto-upload="false"
        drag
        :on-change="handleLoadFileChange"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击载入</em></div>
        <div class="el-upload__tip" slot="tip">
          只能加载标准 JSON 格式文件
        </div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="loadvisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="handleLoad">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {} from "vue";
import boxPage from "./boxPage.vue";
import { savePageList, getPageList, downloadBlob } from "@/util/util";
import { TimeSelect } from "element-ui";
//
export default {
  components: { boxPage },
  data: () => ({
    formPage: { name: "" },
    currentPage: {},
    addvisible: false,
    viewvisible: false,
    loadvisible: false,
    list: [],
    extColumns: [],
    search: "",
    viewBg: "#000",
    viewData: {},
    currentLoadData:undefined,
  }),
  computed: {
    names() {
      return this.list.map((e) => e.name);
    },
    filterList() {
      const s = this.search;
      const l = this.list;
      if (s) {
        return l.filter((d) => d.name.indexOf(s) != -1);
      } else {
        return l;
      }
    },
    baseColumn() {
      return [
        { label: "名称", prop: "name" },
        { label: "样式类", prop: "class", attr: { type: "textarea" } },
      ];
    },
    titleColumn() {
      return [
        { label: "标题样式", prop: "class" },
        { label: "标题 文本", prop: "text" },
        {
          label: "标题名称",
          prop: "name",
          attr: { placeholder: "当标题是组件的时候填写" },
        },
        {
          label: "属性配置",
          prop: "config",
          attr: { type: "textarea" },
        },
      ];
    },
    layoutColumn() {
      return [
        {
          prop: "v",
          name: "el-select",
          label: "请选择分栏布局",
          options: [
            { label: "三栏", value: "three" },
            { label: "两栏", value: "two" },
            { label: "不分栏", value: "zero" },
          ],
          value: "zero",
          extColumn: {
            three: [
              { label: "第一栏样式", prop: "l1" },
              {
                label: "第一栏内容序号",
                prop: "l1n",
                attr: {
                  placeholder: "content 序号，多个序号用 , (英文逗号) 隔开",
                },
              },
              { label: "第二栏样式", prop: "l2" },
              {
                label: "第一栏内容序号",
                prop: "l2n",
                attr: {
                  placeholder: "content 序号，多个序号用 , (英文逗号) 隔开",
                },
              },
              { label: "第三栏样式", prop: "l3" },
              {
                label: "第一栏内容序号",
                prop: "l3n",
                attr: {
                  placeholder: "content 序号，多个序号用 , (英文逗号) 隔开",
                },
              },
            ],
            two: [
              { label: "第一栏样式", prop: "l1" },
              {
                label: "第一栏内容序号",
                prop: "l1n",
                attr: {
                  placeholder: "content 序号，多个序号用 , (英文逗号) 隔开",
                },
              },
              { label: "第二栏样式", prop: "l2" },
              {
                label: "第一栏内容序号",
                prop: "l2n",
                attr: {
                  placeholder: "content 序号，多个序号用 , (英文逗号) 隔开",
                },
              },
            ],
          },
        },
      ];
    },
    contentColumn() {
      const d = [
        {
          label: "边框",
          prop: "border",
          name: "form-items",
          attr: {
            column: [...this.borderColumn],
          },
        },
        { label: "组件样式", prop: "class" },
        {
          label: "组件类型",
          prop: "type",
          name: "el-select",
          options: [
            { label: "datav 组件", value: "datav" },
            //{ label: "echart 组件", value: "echart" },
            { label: "首页3d 柱状图", value: "home-chart" },
            { label: "自定义模块", value: "model" },
            { label: "datav chart", value: "dv-charts" },
          ],
          extColumn: {
            datav: [...this.datavColumn],
            echart: [...this.chartColumn],
            "home-chart": [...this.homeChart],
            model: [...this.modelColumn],
            "dv-charts":[...this.datavChartColumn]
          },
        },
      ];

      return d;
    },
    borderColumn() {
      return [
        {
          label: "选择边框",
          prop: "name",
          name: "el-select",
          options: [
            { label: "无边框", value: "no-border" },
            { label: "样式 1", value: "dv-border-box-1" },
            { label: "样式 2", value: "dv-border-box-2" },
            { label: "样式 3", value: "dv-border-box-3" },
            { label: "样式 4", value: "dv-border-box-4" },
            { label: "样式 5", value: "dv-border-box-5" },
            { label: "样式 6", value: "dv-border-box-6" },
            { label: "样式 7", value: "dv-border-box-7" },
            { label: "样式 8", value: "dv-border-box-8" },
            { label: "样式 9", value: "dv-border-box-9" },
            { label: "样式 10", value: "dv-border-box-10" },
            { label: "样式 11", value: "dv-border-box-11" },
            { label: "样式 12", value: "dv-border-box-12" },
            { label: "样式 13", value: "dv-border-box-13" },
          ],
        },
        { label: "边框样式", prop: "class" },
        {
          label: "属性配置",
          prop: "attr",
          attr: { type: "textarea" },
        },
        { label: "文本配置", prop: "text" },
      ];
    },
    datavColumn() {
      return [
        {
          label: "datav 组件名称",
          prop: "name",
          atrr: { placeholder: "只能输入 datav 组件名称" },
        },
        {
          label: "属性配置",
          prop: "config",
          attr: { type: "textarea" },
        },
        { label: "文本配置", prop: "text" },
      ];
    },
    datavChartColumn(){
      return [
        {
          label: "属性配置",
          prop: "option",
          attr: { type: "textarea" },
        },
      ];
    },
    chartColumn() {
      return [
        // { label: "名称", prop: "name", value: "echart",attr:{disabled:true} },
        { label: "选项", prop: "option", attr: { type: "textarea" } },
        {
          label: "默认选项",
          prop: "defaultOption",
          attr: { type: "textarea" },
        },
      ];
    },
    homeChart() {
      return [
        { label: "默认柱子高度", prop: "dz", name: "el-input-number" },
        { label: "默认柱子颜色", prop: "dc", name: "el-color-picker" },
        { label:"背景图片",prop:"bgurl"},
        {
          label: "图形设置",
          prop: "colors",
          name: "form-set",
          attr: {
            column: [
              { label: "x 轴 ", prop: "x", name: "number-range" },
              { label: "y 轴 ", prop: "y", name: "number-range" },
              { label: "柱子高度（z）", prop: "z", name: "el-input-number" },
              { label: "柱子颜色（c）", prop: "c", name: "el-color-picker" },
              { label: "显示的名称", prop: "name" },
            ],
          },
        },
        {
          label: "图片(base64编码)",
          prop: "imgurl",
          key: "content.imgurl",
          attr: { type: "textarea" },
        },
        { label: "选项", prop: "option", attr: { type: "textarea" } },
      ];
    },
    modelColumn() {
      return [
        { label: "名称", prop: "name" },
        { label: "描述", prop: "desc" },
        { label: "选项", prop: "attr", attr: { type: "textarea" } },
      ];
    },
  },
  methods: {
    handleOpenAdd() {
      this.formPage = { name: "", class: "", border: {}, content: [] };
      this.addvisible = true;
    },
    handleAdd() {
      const n = this.formPage.name;
      if (!n) {
        this.$message("请输入名称");
        return;
      }
      if (this.names.includes(n)) {
        this.$message.warning("该名称已存在，请重新输入");
        return;
      }
      const d = { ...this.formPage, class: "", border: {}, content: [] };
      this.list = [...this.list, d];
      //
      this.currentPage = d;
      this.formPage = {};
      //
      this.addvisible = false;
    },
    handleSelectItem(item) {
      this.currentPage = item;
    },
    handleTypeSelect(v) {
      console.log(v);
      switch (v) {
        case "datav":
          this.extColumns = [...this.datavColumn];
          break;
        case "echart":
          this.extColumns = [...this.chartColumn];
          break;
        case "home-chart":
          this.extColumns = [...this.homeChart];
          break;
        case "model":
          this.extColumns = [...this.modelColumn];
          break;
      }
    },
    handlePreview() {
      // console.log('====>',JSON.stringify(this.currentPage,null,2))
      console.log("====>", JSON.stringify(this.list, null, 2));
      this.viewvisible = true;
      this.viewData = JSON.parse(JSON.stringify(this.currentPage));
    },
    handleSave() {
      savePageList(this.list);
      this.$message({
        type: "success",
        message: "保存成功!",
      });
    },
    handleDelete() {
      this.$confirm("此操作将永久删除该页面, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const n = this.currentPage.name;
          this.list = this.list.filter((d) => d.name !== n);
          this.handleSave();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async initPageList() {
      this.list = await getPageList();
    },
    handleDown() {
      const n = this.currentPage.name;
      const d = JSON.stringify(this.currentPage,null,2);
      if (n && d) {
        const name = `${n}.json`;
        const blob = new Blob([d]);
        downloadBlob(blob, name);
      }
    },
    handleLoadFileChange(file){
      console.log('=======file',file)
      const reader = new FileReader();
      reader.onload = () => {
        this.handleLoad(reader.result)
      }
      reader.readAsText(file.raw)
    },
    handleLoad(s) {
      try {
        const d = JSON.parse(s)
        const n = d.name;
        if(!n || this.names.includes(n)){
          this.$message.warning("该页面数据中的名称已存在或者名称有误，请替换名称再导入")
          return;
        }
        this.list = [...this.list,d];
        this.currentPage = d;
      } catch (error) {
        console.error(error);
        this.$message.error('解析JSON 数据异常，请检查数据格式是否有误')
      }
    },
  },
  created() {
    this.initPageList();
  },
};
</script>
